package com.weizai.carshop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.weizai.carshop.common.result.PageResult;
import com.weizai.carshop.mapper.CartListMapper;
import com.weizai.carshop.model.dto.QueryShopCateDto;
import com.weizai.carshop.model.entiity.CartListEntity;
import com.weizai.carshop.model.vo.CartListVo;
import com.weizai.carshop.service.CartListService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@RequiredArgsConstructor
public class CartListServiceImpl extends ServiceImpl<CartListMapper, CartListEntity>  implements CartListService {

    private final CartListMapper cartListMapper;

    /*
    * 更新购物车
    * */
    @Override
    public void updateCart(CartListEntity args) {

        // 判断是否有相同的商品加入购物车(并且规格也相同)
        CartListEntity cart = lambdaQuery()
                .eq(CartListEntity::getGoodsId, args.getGoodsId())
                .eq(CartListEntity::getGoodsNorm, args.getGoodsNorm())
                .one();

        if(cart != null) {
            cart.setGoodsNum(cart.getGoodsNum() + args.getGoodsNum());
            cart.setUpdateTime(LocalDateTime.now());
            updateById(cart);
            return;
        }

        // 判断为新增或编辑
        if(args.getId() == null) {
            args.setCreateTime(LocalDateTime.now());
            args.setUpdateTime(LocalDateTime.now());
        }else {
            args.setUpdateTime(LocalDateTime.now());
        }

        this.saveOrUpdate(args);
    }

    /*
    * 查询购物车接口
    * */
    @Override
    public PageResult queryCartList(QueryShopCateDto dto) {
        // 参数校验
        dto.validate();

        // 分页查询数据
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<CartListVo> page = cartListMapper.queryCart(dto);

        System.out.println(page.getTotal());

        return new PageResult(page.getTotal(), page.getResult());
    }
}
